package cn.bellychang.leetcode.question001;

import java.util.HashMap;
import java.util.Map;

/**
 * @author ChangLiang
 * @date 2020/9/6
 */
public class Solution3 {

    /**
     * Approach 3: One-pass Hash Table
     *
     * @param nums
     * @param target
     * @return
     */
    public int[] twoSum(int[] nums, int target) {

        Map<Integer, Integer> map = new HashMap<>(nums.length);
        // While we iterate and inserting elements into the table,
        // we also look back to check if current element's complement already exists in the table.
        for (int i = 0; i < nums.length; i++) {
            int anotherNum = target - nums[i];
            if (map.containsKey(anotherNum)) {
                Integer indiceY = map.get(anotherNum);
                if (indiceY != i) {
                    return new int[]{indiceY, i};
                }
            }
            map.put(nums[i], i);
        }
        return new int[]{};
    }
}
